package com.zmj.sy.mom.srv.aps.utils.schedulerole.impl;

import com.google.common.collect.Lists;
import com.zmj.sy.mom.srv.aps.bean.bo.CacheFactory;
import com.zmj.sy.mom.srv.aps.bean.entity.order.ApsBatch;
import com.zmj.sy.mom.srv.aps.bean.entity.order.ApsOrder;
import com.zmj.sy.mom.srv.aps.bean.entity.order.Order;
import com.zmj.sy.mom.srv.aps.bean.vo.apsorder.ApsOrderScheduleReqVo;
import com.zmj.sy.mom.srv.aps.mapper.OrderMapper;
import com.zmj.sy.mom.srv.aps.utils.schedulerole.ScheduleRole;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@RequiredArgsConstructor
@Component
public class MixScheduleRole implements ScheduleRole {

    private final OrderMapper orderMapper;

    @Override
    public List<ApsOrder> sort(List<ApsOrder> apsOrders, ApsOrderScheduleReqVo reqVo) {
        // 移动的数据在seq字段中存着

        // 1.先根据order的顺序排序
        List<Order> orders = orderMapper.selectBatchIds(apsOrders.stream().map(ApsOrder::getOrderId).collect(Collectors.toList()));
        orders.sort(Comparator.comparing(Order::getSeq));

        // 2.再根据每一订单一包的轮次开始往后排序
        Map<Integer, List<ApsOrder>> orderMap = apsOrders.stream().collect(Collectors.groupingBy(ApsOrder::getOrderId));
        Map<Integer, Long> collect = apsOrders.stream().collect(Collectors.groupingBy(ApsOrder::getOrderId, Collectors.counting()));
        int max = collect.values().stream().max(Long::compareTo).orElse(0L).intValue();

        List<ApsOrder> result = Lists.newArrayList();
        for (int i = 0; i < max; i++) {
            for (Order order : orders) {
                List<ApsOrder> currentOrder = orderMap.get(order.getId());
                currentOrder.sort(Comparator.comparing(ApsOrder::getSeq));// 效率低，可以优化
                if(i >= currentOrder.size()){
                    continue;
                }
                result.add(currentOrder.get(i));
            }
        }

        return result;
    }
    @Override
    public List<ApsOrder> sort(CacheFactory reqVo, ApsBatch batch, List<Order> orders) {
        return Collections.emptyList();
    }
    @Override
    public Integer getMyCode() {
        return MIX;
    }
}
